package com.aiden.app.common.http.converter

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type

/**
 * 对请求到的数据做处理，重写了 {@link GsonConverterFactory}，并重写相关调用类
 * @author yanggeng
 * @date 2018/12/12 17:12
 */
class GsonConverterFactory(private var gson: Gson) : Converter.Factory() {

    companion object {
        var factory: GsonConverterFactory? = null

        fun create(): GsonConverterFactory {
            if (factory == null) {
                synchronized(GsonConverterFactory::class) {
                    if (factory == null) {
                        factory = GsonConverterFactory(Gson())
                    }
                }
            }
            return factory!!
        }
    }

    override fun responseBodyConverter(type: Type, annotations: Array<Annotation>,
                                       retrofit: Retrofit): Converter<ResponseBody, *> {
        val adapter = gson.getAdapter(TypeToken.get(type))
        return GsonResponseBodyConverter(gson, adapter)
    }

    override fun requestBodyConverter(type: Type,
                                      parameterAnnotations: Array<Annotation>, methodAnnotations: Array<Annotation>, retrofit: Retrofit): Converter<*, RequestBody> {
        val adapter = gson.getAdapter(TypeToken.get(type))
        return GsonRequestBodyConverter(gson, adapter)
    }


}